//
//  DRDevicesVC.m
//  DoctorRen
//
//  Created by Macx on 2018/11/21.
//

#import "DRDevicesVC.h"
#import "DRDeviceCell.h"
#import "DRMineDataModel.h"
#import <Masonry/Masonry.h>
#import "DRPickerView.h"

@interface DRDevicesVC ()<UITableViewDelegate , UITableViewDataSource, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segment;
@property (weak, nonatomic) IBOutlet UIButton *addRecordBtn;
@property (weak, nonatomic) IBOutlet UIButton *buyBtn;

@property (nonatomic, strong) UIWebView *webView;

@property (weak, nonatomic) UITextField *weightTF;
@property (weak, nonatomic) UITextField *sugarTF;
@property (weak, nonatomic) UITextField *pressureTF;

@property (nonatomic, strong) NSArray <NSString *>* weightArray;
@property (nonatomic, strong) NSArray <NSString *>* decimalsArray;
@property (nonatomic, strong) NSArray <NSString *>* sugarArray;

@end

@implementation DRDevicesVC{
    NSString *_url;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView = [UIView new];
    self.addRecordBtn.layer.cornerRadius = 20;
    self.buyBtn.layer.borderColor = [There_Green CGColor];
    self.buyBtn.layer.borderWidth = 1;
    self.buyBtn.layer.cornerRadius = 20;
    //http://rsjkkj.com/index.php?s=/ucenter/devicebefore.html&dontpush=1
    _url = [NSString stringWithFormat:@"http://rsjkkj.com/dist/#/my/healthData?token=%@&isBack=1",[DRLoginDataModel getUserToken]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
    UIView *contentView = [UIView new];
    [contentView setHidden:YES];
    [self.view addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.tableView);
        make.left.right.bottom.mas_equalTo(0);
    }];
    [contentView addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(0);
    }];
    contentView.clipsToBounds = YES;

}

- (IBAction)clickBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)clickAddRecordBtn:(id)sender {
    [DRMineDataModel saveDeviceDataWith:[self.weightTF.text stringByReplacingOccurrencesOfString:@"KG" withString:@""]
                                  sugar:[self.sugarTF.text stringByReplacingOccurrencesOfString:@"mmol/L" withString:@""]
                                presure:[self.pressureTF.text stringByReplacingOccurrencesOfString:@"(高压/低压)" withString:@""]
                                success:^{
                                            [SVProgressHUD showSuccessWithStatus:@"添加成功"];
                                    }
                                andFail:^(NSError *error) {
                                            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                                    }];
}
- (IBAction)clickBuyBtn:(id)sender {
    [self pushWebViewWithUrl:[NSString stringWithFormat:@"http://rsjkkj.com/dist/#/toBug?isBack=1&token=%@",[DRLoginDataModel getUserToken]]];
    self.hidesBottomBarWhenPushed = YES;
}

- (IBAction)clickSegment:(UISegmentedControl *)sender {
    BOOL isFinish = sender.selectedSegmentIndex == 0;
    [self.tableView setHidden:!isFinish];
    [self.addRecordBtn setHidden:!isFinish];
    [self.buyBtn setHidden:!isFinish];
    [self.webView.superview setHidden:isFinish];
    if (sender.selectedSegmentIndex == 1) {
        [self.webView reload];
    }
}



-(UIWebView *)webView{
    if (!_webView) {
        _webView = [[UIWebView alloc] init];
        _webView.scrollView.bounces = NO;
    }
    return _webView;
}


-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    DRPickerView *pickerView = [[NSBundle mainBundle] loadNibNamed:@"DRPickerView" owner:self options:nil].firstObject;
    pickerView.frame = self.view.frame;
    [self.view addSubview:pickerView];
    textField.inputView = pickerView;
    
    NSMutableArray *data = [NSMutableArray array];
    NSInteger defaultRow1 = 0;
    NSInteger defaultRow2 = 0;
    if (textField == self.weightTF) {
        [data addObject:self.weightArray];
        [data addObject:self.decimalsArray];
         NSString *str = [textField.text stringByReplacingOccurrencesOfString:@"KG" withString:@""];
        if (![NSString isNullOrEmpty:str] && [str componentsSeparatedByString:@"."].count > 0) {
            NSArray *arr = [str componentsSeparatedByString:@"."];
            defaultRow1 = [self.weightArray indexOfObject:arr[0]];
            defaultRow2 = [arr[1] integerValue];
        }else{
            defaultRow1 = 35;
        }
        [pickerView setTitle:@"体重（KG）"];
    } else if (textField == self.sugarTF){
        [data addObject:self.sugarArray];
        [data addObject:self.decimalsArray];
        NSString *str = [textField.text stringByReplacingOccurrencesOfString:@"mmol/L" withString:@""];
        if (![NSString isNullOrEmpty:str] && [str componentsSeparatedByString:@"."].count > 0) {
            
            NSArray *arr = [str componentsSeparatedByString:@"."];
            defaultRow1 = [self.sugarArray indexOfObject:arr[0]];
            defaultRow2 = [arr[1] integerValue];
        }else{
            defaultRow1 = 6;
        }
        [pickerView setTitle:@"血糖（mmol/L）"];
    }else{
        [data addObject:self.weightArray];
        [data addObject:self.weightArray];
        NSString *str = [textField.text stringByReplacingOccurrencesOfString:@"(高压/低压)" withString:@""];
        if (![NSString isNullOrEmpty:str] && [str componentsSeparatedByString:@"/"].count > 1) {
            
            NSArray *arr = [str componentsSeparatedByString:@"/"];
            defaultRow1 = [self.weightArray indexOfObject:arr[0]];
            defaultRow2 = [self.weightArray indexOfObject:arr[1]];
        }else{
            defaultRow1 = 140;
            defaultRow2 = 90;
        }
        [pickerView setTitle:@"血压（高压/低压）"];
    }

    [pickerView setPickerData:[data copy]];
    [pickerView setDefaultRow:defaultRow1 inComponent:0];
    [pickerView setDefaultRow:defaultRow2 inComponent:1];
    pickerView.confirmBlock = ^(NSString * _Nonnull str1, NSString * _Nonnull str2) {
        if (textField == self.weightTF) {
            textField.text = [NSString stringWithFormat:@"%@%@KG",str1,str2];
        } else if (textField == self.sugarTF){
            textField.text = [NSString stringWithFormat:@"%@%@mmol/L",str1, str2];
        }else{
            textField.text = [NSString stringWithFormat:@"%@/%@(高压/低压)",str1, str2];
        }
    };
    return NO;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    DRDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DRDeviceCell"];
    switch (indexPath.row) {
        case 0:
        {
            cell.deviceName.text = @"体重秤";
            self.weightTF = cell.textField;
            self.weightTF.delegate = self;
        }
            break;
        case 1:
        {
            cell.deviceName.text = @"血糖仪";
            self.sugarTF = cell.textField;
            self.sugarTF.delegate = self;
        }
            break;
        default:
        {
            cell.deviceName.text = @"血压仪";
            self.pressureTF = cell.textField;
            self.pressureTF.delegate = self;
        }
            break;
    }
    WEAKSELF
    cell.bindAction = ^{

    };
    
    cell.readAction = ^{
        STRONGSELF
        [strongSelf presentBindDeviceVC:indexPath.row block:^(NSInteger type, NSString *value) {
            if ([value integerValue] == 0) {
                return ;
            }
            switch (type) {
                case 0:
                    strongSelf.weightTF.text = [NSString stringWithFormat:@"%@KG",value];;
                    break;
                case 1:
                    strongSelf.sugarTF.text = [NSString stringWithFormat:@"%@mmol/L",value];;
                    break;
                default:
                    strongSelf.pressureTF.text = [NSString stringWithFormat:@"%@(高压/低压)",value];
                    break;
            }
        }];
        
    };
    return cell;
}

-(NSArray<NSString *> *)decimalsArray{
    if (!_decimalsArray) {
        _decimalsArray = @[@".0",@".1",@".2",@".3",@".4",@".5",@".6",@".7",@".8",@".9"];
    }
    return _decimalsArray;
}

-(NSArray<NSString *> *)sugarArray{
    if (!_sugarArray) {
        NSMutableArray *arr = [NSMutableArray array];
        for (int i = 1; i < 29; i++) {
            [arr addObject:[@(i) stringValue]];
        }
        _sugarArray = [arr copy];
    }
    return _sugarArray;
}

-(NSArray<NSString *> *)weightArray{
    if (!_weightArray) {
        NSMutableArray *arr = [NSMutableArray array];
        for (int i = 10; i < 250; i++) {
            [arr addObject:[@(i) stringValue]];
        }
        _weightArray = [arr copy];
    }
    return _weightArray;
}

@end
